<?php
class ProductBusiness {
	
	public function getProducts(){
		$db = Zend_Db_Table::getDefaultAdapter();

		$select = $db->fetchAll("SELECT * FROM pr_product where id_category = 2 ORDER BY RAND() LIMIT 0,5;");

		return $select;

	}
	
	public function getProductsRandom(){
		$db = Zend_Db_Table::getDefaultAdapter();

		$select = $db->fetchAll("SELECT * FROM pr_product ORDER BY RAND() LIMIT 0,3;");

		return $select;

	}
	
	public function getAllProducts(){
		$db = Zend_Db_Table::getDefaultAdapter();

		$select = $db->fetchAll("SELECT * FROM pr_product ORDER id_product() asc");

		return $select;

	}
	
	public function filterProducts($orderBy, $param, $filter){
		$db = Zend_Db_Table::getDefaultAdapter();

		try{
			
			$orderBy = explode("-", $orderBy);
			
			
			$query = ' SELECT * FROM pr_product pr
			where pr.id_product is not NULL ';
			
			
			if($filter['search'] != null){
				$query = $query . ' and pr.name like "%'.$filter['search'].'%" OR pr.title like "%'.$filter['search'].'%" ';
			}
			
			if($filter['title'] != null){
				$query = $query . ' and pr.title like "%'.$filter['title'].'%" ';
			}
			
			if($filter['category'] != null){
				$query = $query . ' and pr.id_category = '.$filter['category'].' ';
			}
			
			if($orderBy != null && sizeof($orderBy) > 1){
				$query = $query . ' order by pr.status DESC, '.$orderBy[0].' '.$orderBy[1].' ';
			}
			else{
				$query = $query . ' order by pr.status DESC, pr.price ASC';
			}
			
			$select = $db->fetchAll($query);
			
		}catch (Exception $e){
			echo $e;
		}

		return $select;
	}
	
	public function getRateByUser($client, $id){
		$db = Zend_Db_Table::getDefaultAdapter();

		$select = $db->fetchAll("SELECT * FROM pr_rating where id_client = '".$client."' and id_product = '".$id."'");

		return $select;
	}
	
	public function getRateProduct($id){
		$db = Zend_Db_Table::getDefaultAdapter();

		$select = $db->fetchAll("SELECT * FROM pr_rating where id_product = '".$id."'");

		return $select;
	}
	
	public function rateProduct($data){
	try {
			$db = Zend_Db_Table::getDefaultAdapter();
			$lastId = $db->lastInsertId('pr_rating');
			$array['id_rating'] = $lastId;
			$query = $db->insert('pr_rating', $data);

		} catch (Exception $e) {
			echo $e;
		}
	}
	
}